package com.loongtech.bi.action.monitor;

import com.loongtech.bi.action.authManagement.ResultData;
import com.loongtech.bi.entity.system.EntityMonitorConfig;
import com.loongtech.bi.entity.system.EntityMonitorGroupConfig;
import com.loongtech.bi.entity.system.EntityMonitorUserGroup;
import com.loongtech.bi.manager.system.*;
import com.loongtech.bi.support.Session;
import com.loongtech.core.util.RetCode;
import com.loongtech.core.util.Time;
import com.loongtech.core.util.Utils;
import org.quartz.Trigger.TriggerState;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * Author: yuri
 * Description: 监控组别配置
 * Date: 16:42 2017/5/17
 */
@RestController
@Scope("prototype")
@RequestMapping("/monitorgroup")
public class MonitorGroupConfigAction {
    @Resource
    private Session session;
    @Resource
    private SysLogManager sysLogManager;
    @Resource
    private BiMonitorGroupConfigManager biMonitorGroupConfigManager;
    @Resource
    private BiMonitorConfigManager biMonitorConfigManager;
    @Resource
    private BiMonitorUserGroupManager biMonitorUserGroupManager;
    @Resource
    private SyncInfoLogManager syncInfoLogManager;

    /**
     * 查询
     */
    @RequestMapping(value = "list.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<?> searchByCriteria(EntityMonitorGroupConfig entity) {
        List<EntityMonitorGroupConfig> list;
        try {
            list = biMonitorGroupConfigManager.searchByCriteria(entity);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
//        if (list != null && list.size() > 0) {
//            for (EntityMonitorGroupConfig groupConfig : list) {
//                String gameid = groupConfig.getGameId();
//                for (Map.Entry<String, String> entry : projectIdNameMap.entrySet()) {
//                    gameid = gameid.replace(entry.getKey() + ",", entry.getValue() + ",");
//                }
//                groupConfig.setGameName(gameid);
//            }
//        }
        return new ResultData<>(RetCode.eSuccess.getErrorcode(), list);
    }

    /**
     * 增加
     */
    @RequestMapping(value = "add.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> addGroup(EntityMonitorGroupConfig entity) {
        if (Utils.isEmptyStr(entity.getGroupName())) {
            return new ResultData<>(RetCode.eEmptyUserNameError.getErrorcode(), RetCode.eEmptyUserNameError.getErrorMsg());
        }
//        if (entity.getGameId() == null) {
//            return new ResultData<>(RetCode.eEmptyId.getErrorcode(), RetCode.eEmptyId.getErrorMsg());
//        }
        if (Utils.isEmptyStr(entity.getVoiceTemplate()) && containCheck("语音号", entity.getNotifyTypeList())) {
            return new ResultData<>(RetCode.eEmptyVoiceTemplateError.getErrorcode(), RetCode.eEmptyVoiceTemplateError.getErrorMsg());
        }
        try {
            biMonitorGroupConfigManager.addGroup(entity);
            sysLogManager.addLog(session.getUserName(), "增加告警组别成功:" + entity.getGroupName());

            StringBuilder insertSQL = new StringBuilder("insert into bi_monitor_groupconfig(groupName,voiceTemplate,notifyType,description,createTime) values");
            insertSQL.append("('").append(entity.getGroupName()).append("','").append(entity.getVoiceTemplate()).append("','").append(entity.getNotifyType()).append("','").
                    append(entity.getDescription()).append("',").append(Time.currentTime()).append(")");
            Set<String> gameId = SysProjectManager.projectIdNameMap.keySet();
            for (String gid : gameId) {
                syncInfoLogManager.add(gid, insertSQL.toString());
            }

            return ResultData.success();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    /**
     * 删除
     */
    @RequestMapping(value = "delete.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> delGroup(@RequestParam(value = "id") Integer id) {
        try {
            //数据库无此id
            EntityMonitorGroupConfig cur = biMonitorGroupConfigManager.get(id);
            if (cur == null) {
                return new ResultData<>(RetCode.eNotExistGourp.getErrorcode(), RetCode.eNotExistGourp.getErrorMsg());
            }
            //分组属于某个任务时，根据任务状态判断是否能删除
            EntityMonitorConfig res = biMonitorConfigManager.getByQuery("from EntityMonitorConfig where groupId = ? and (status = ? or status = ? or status = ? or status = ?)", id, TriggerState.BLOCKED.name(), TriggerState.NORMAL.name(), TriggerState.PAUSED.name(), TriggerState.ERROR.name());
            if (res != null) {
                return new ResultData<>(RetCode.eGroupBelongToMonitor.getErrorcode(), RetCode.eGroupBelongToMonitor.getErrorMsg());
            }
            //分组下有用户，不能删除
            EntityMonitorUserGroup res2 = biMonitorConfigManager.getByQuery("from EntityMonitorUserGroup where groupId = ? ", id);
            if (res2 != null) {
                return new ResultData<>(RetCode.eGroupHasUser.getErrorcode(), RetCode.eGroupHasUser.getErrorMsg());
            }
            biMonitorGroupConfigManager.delGroup(id);
            Set<String> gameId = SysProjectManager.projectIdNameMap.keySet();
            for (String gid : gameId) {
                syncInfoLogManager.add(gid, "delete from bi_monitor_groupconfig where id = " + gid );
            }
            sysLogManager.addLog(session.getUserName(), "告警分组删除成功");
            return ResultData.success();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    /**
     * 修改
     */
    @RequestMapping(value = "modify.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> modifiyGroup(EntityMonitorGroupConfig entity) {
        if (Utils.isEmptyStr(entity.getGroupName())) {
            return new ResultData<>(RetCode.eEmptyUserNameError.getErrorcode(), RetCode.eEmptyUserNameError.getErrorMsg());
        }
//        if (entity.getGameId() == null) {
//            return new ResultData<>(RetCode.eEmptyId.getErrorcode(), RetCode.eEmptyId.getErrorMsg());
//        }
        if (Utils.isEmptyStr(entity.getVoiceTemplate()) && containCheck("语音号", entity.getNotifyTypeList())) {
            return new ResultData<>(RetCode.eEmptyVoiceTemplateError.getErrorcode(), RetCode.eEmptyVoiceTemplateError.getErrorMsg());
        }
        try {
            EntityMonitorGroupConfig cur = biMonitorGroupConfigManager.get(entity.getId());
            if (cur != null) {
                entity.setCreateTime(cur.getCreateTime());
                biMonitorGroupConfigManager.modifiyGroup(entity);

                StringBuilder updateSQL = new StringBuilder("update bi_monitor_groupconfig set groupName = ");
                updateSQL.append("'").append(entity.getGroupName()).append("',voiceTemplate = '").append(entity.getNotifyType()).append("',description = '").append(entity.getDescription()).
                        append("',createTime = ").append(Time.currentTime()).append(" where  id = ").append(entity.getId());
                Set<String> gameId = SysProjectManager.projectIdNameMap.keySet();
                for (String gid : gameId) {
                    syncInfoLogManager.add(gid, updateSQL.toString());
                }
                sysLogManager.addLog(session.getUserName(), "告警组别修改成功");
                return ResultData.success();
            } else {
                return new ResultData<>(RetCode.eNotExistGourp.getErrorcode(), RetCode.eNotExistGourp.getErrorMsg());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    private boolean containCheck(String str, List<String> list) {
        if (list == null || list.size() == 0) {
            return false;
        }
        for (String strInList : list) {
            if (strInList.equals(str)) {
                return true;
            }
        }
        return false;
    }
}
